<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="科目" prop="subjectId">
        <el-select v-model="queryParams.subjectId" placeholder="请选择科目">
            <el-option
                v-for="subject in subjectOptions"
                :key="subject.subjectId"
                :label="subject.subjectName"
                :value="subject.subjectId"
              />
          </el-select>
      </el-form-item>
      <el-form-item label="教学组" prop="deptId">
        <treeselect style="width:200px" v-model="queryParams.deptId" :options="campusOptions" 
                :multiple="false" :disableBranchNodes="true"
                :show-count="true" placeholder="请选择归属教学组" />
      </el-form-item>
      <!--
      <el-form-item label="计划编号" prop="teachPlanCode">
        <el-input
          v-model="queryParams.teachPlanCode"
          placeholder="请输入教学计划编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      -->
      <el-form-item label="计划名称" prop="teachPlanName">
        <el-input
          v-model="queryParams.teachPlanName"
          placeholder="请输入教学计划名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--
      <el-form-item label="班级类别" prop="classType">
        <el-select v-model="queryParams.classType" placeholder="请选择班级类别" clearable size="small">
          <el-option
                v-for="dict in classTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item label="科别" prop="subjectType">
        <el-select v-model="queryParams.subjectType" placeholder="请选择科别" clearable size="small">
          <el-option
                v-for="dict in subjectTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item label="计划天数" prop="teachPlanDays">
        <el-input
          v-model="queryParams.teachPlanDays"
          placeholder="请输入计划天数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上课次数" prop="teachTimes">
        <el-input
          v-model="queryParams.teachTimes"
          placeholder="请输入上课次数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
        </el-select>
      </el-form-item>
      -->
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['edu:teachPlan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['edu:teachPlan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['edu:teachPlan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['edu:teachPlan:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="table"
      stripe
      border 
      v-loading="loading" :data="teachPlanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand">
          <template slot-scope="scope">
            <el-table
            :data="scope.row.eduTeachContentList"
            style="width: 100%">
            <el-table-column v-if="false" label="教学计划内容ID" align="center" prop="contentId" />
            <el-table-column  v-if="false" label="教学计划ID" align="center" prop="teachPlanId" />
            <el-table-column label="课次" align="center" prop="courseTimes" />
            <el-table-column label="教学内容" align="center" prop="content" />
            <el-table-column label="教学重点" align="center" prop="keyPoints" />
            <el-table-column label="教学目标" align="center" prop="targets" />
            <el-table-column label="教学方法" align="center" prop="methods" />
            <el-table-column label="状态" :formatter="statusFormat" align="center" prop="status" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdateContent(scope.row)"
                  v-hasPermi="['edu:teachContent:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteContent(scope.row)"
                  v-hasPermi="['edu:teachContent:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>      
      </el-table-column>
      <!--<el-table-column label="教学计划ID" align="center" prop="teachPlanId" />-->
      <el-table-column label="科目" align="center" prop="subjectName" />
      <el-table-column label="教学组" align="center" prop="deptName" />
      <el-table-column label="教学计划编号" align="center" prop="teachPlanCode" />
      <el-table-column label="教学计划名称" align="center" prop="teachPlanName" />
      <el-table-column label="班级类别" :formatter="classTypeFormat" align="center" prop="classType" />
      <el-table-column label="科别" :formatter="subjectTypeFormat" align="center" prop="subjectType" />
      <el-table-column label="计划天数" align="center" prop="teachPlanDays" />
      <!--<el-table-column label="总教学内容" align="center" prop="content" />
      <el-table-column label="总教学要求" align="center" prop="demands" />-->
      <el-table-column label="上课次数" align="center" prop="teachTimes" />
      <el-table-column label="状态" :formatter="statusFormat" align="center" prop="status" />
      <el-table-column label="操作" min-width="220px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleAddContent(scope.row)"
                v-hasPermi="['edu:hColleges:edit']"
              >新增内容</el-button>
          <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="expandChange(scope.row)"
                v-hasPermi="['edu:hColleges:edit']"
              >查看内容</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edu:teachPlan:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['edu:teachPlan:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改教学计划信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeName" @tab-click="handleTabChange">
          <el-tab-pane label="基本信息" name="first">
            <el-form-item label="科目" prop="subjectId">
              <el-select v-model="form.subjectId" placeholder="请选择科目">
                <el-option
                    v-for="subject in subjectOptions"
                    :key="subject.subjectId"
                    :label="subject.subjectName"
                    :value="subject.subjectId"
                  />
              </el-select>
            </el-form-item>
            <el-form-item label="教学组" prop="deptId">
              <treeselect style="width:200px" v-model="form.deptId" :options="campusOptions" 
                    :multiple="false" :disableBranchNodes="true"
                    :show-count="true" placeholder="请选择归属教学组" />
            </el-form-item>
            <el-form-item label="教学计划编号" prop="teachPlanCode">
              <el-input v-model="form.teachPlanCode" placeholder="请输入教学计划编号" />
            </el-form-item>
            <el-form-item label="教学计划名称" prop="teachPlanName">
              <el-input v-model="form.teachPlanName" placeholder="请输入教学计划名称" />
            </el-form-item>
            <el-form-item label="班级类别" prop="classType">
              <el-select v-model="form.classType" placeholder="请选择班级类别">
                <el-option
                    v-for="dict in classTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
              </el-select>
            </el-form-item>
            <el-form-item label="科别" prop="subjectType">
              <el-select v-model="form.subjectType" placeholder="请选择科别">
                <el-option
                    v-for="dict in subjectTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
              </el-select>
            </el-form-item>
            <el-form-item label="计划天数" prop="teachPlanDays">
              <el-input v-model="form.teachPlanDays" placeholder="请输入计划天数" />
            </el-form-item>
            <el-form-item label="上课次数" prop="teachTimes">
              <el-input v-model="form.teachTimes" placeholder="请输入上课次数" />
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                        <el-radio
                          v-for="dict in statusOptions"
                          :key="dict.dictValue"
                          :label="dict.dictValue"
                        >{{dict.dictLabel}}</el-radio>
                      </el-radio-group>
            </el-form-item>
          </el-tab-pane>  
          <el-tab-pane label="教学内容" name="second">
            <el-form-item label="总教学内容">
              <editor v-model="form.content" :min-height="192"/>
            </el-form-item>
            <el-form-item label="总教学要求" prop="demands">
              <!--<el-input v-model="form.demands" type="textarea" placeholder="请输入内容" />-->
              <editor v-model="form.demands" :min-height="192"/>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="课件" name="third">
            <el-form-item label="附件路径" prop="coursewareUrl">
              <el-upload
                ref="upload"
                :limit="1"
                :headers="upload.headers"
                :action="upload.url"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                :file-list="fileList"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                drag
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitFileForm">上 传</el-button>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="titleContent" :visible.sync="openContent" width="800px" append-to-body>
      <el-form ref="formContent" :model="formContent" :rules="rulesContent" label-width="120px">
        <!--
        <el-form-item label="教学计划" prop="teachPlanId">
          <el-input v-model="formContent.teachPlanId" placeholder="请输入教学计划ID" style="width:300px" />
        </el-form-item>
        -->
        <el-form-item label="课次" prop="courseTimes">
          <el-input v-model="formContent.courseTimes" placeholder="请输入课次" />
        </el-form-item>
        <el-form-item label="教学内容" >
          <editor v-model="formContent.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="教学重点" prop="keyPoints">
          <el-input v-model="formContent.keyPoints" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="教学目标" prop="targets">
          <el-input v-model="formContent.targets" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="教学方法" prop="methods">
          <el-input v-model="formContent.methods" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formContent.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div style="margin-left:50px;">
        <el-button size="mini" type="primary" @click="submitFormContent">确 定</el-button>
        <el-button size="mini" @click="cancelContent">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTeachPlan, getTeachPlan, delTeachPlan, addTeachPlan, updateTeachPlan, exportTeachPlan } from "@/api/edu/teachPlan";
import { listTeachContentByPlanId, getTeachContent, delTeachContent, addTeachContent, updateTeachContent, exportTeachContent } from "@/api/edu/teachContent";
import { getToken } from "@/utils/auth";
import Editor from '@/components/Editor';
import { treeselectByType } from "@/api/system/dept";
import { getSubjectsAll } from "@/api/edu/subjects";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "TeachPlan",
  components: { Editor, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教学计划信息表格数据
      teachPlanList: [],
      teachContentList: [],
      fileList: [],
      subjectOptions: [],
      campusOptions: [],
      statusOptions: [],
      classTypeOptions: [],
      subjectTypeOptions: [],
      activeName: 'first',
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      // 弹出层标题
      title: "",
      titleContent: "",
      // 是否显示弹出层
      open: false,
      openContent: false,
      expandRow: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectId: null,
        deptId: null,
        teachPlanCode: null,
        teachPlanName: null,
        classType: null,
        subjectType: null,
        teachPlanDays: null,
        content: null,
        demands: null,
        teachTimes: null,
        status: null,
      },
      // 表单参数
      form: {},
      formContent: {},
      // 表单校验
      rules: {
        subjectId: [
          { required: true, message: "科目ID不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "教学组不能为空", trigger: "blur" }
        ],
      },
      rulesContent: {
        teachPlanId: [
          { required: true, message: "教学计划ID不能为空", trigger: "blur" }
        ],
        courseTimes: [
          { required: true, message: "课次不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    
    this.getSubjects();
    this.queryCampus();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("edu_class_type").then(response => {
      this.classTypeOptions = response.data;
    });
    this.getDicts("edu_subject_type").then(response => {
      this.subjectTypeOptions = response.data;
    });
    this.getList();
  },
  methods: {
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    classTypeFormat(row, column) {
      return this.selectDictLabel(this.classTypeOptions, row.classType);
    },
    subjectTypeFormat(row, column) {
      return this.selectDictLabel(this.subjectTypeOptions, row.subjectType);
    },
    queryCampus() {
      // 查询校区（deptType = 4 教学组）
      treeselectByType("4").then(response => {
        this.campusOptions = response.data;
      })
    },
    getSubjects() {
      getSubjectsAll().then(response => {
        this.subjectOptions = response.data
      })
    },
    /** 查询教学计划信息列表 */
    getList() {
      this.loading = true;
      listTeachPlan(this.queryParams).then(response => {
        this.teachPlanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        teachPlanId: null,
        subjectId: null,
        deptId: null,
        teachPlanCode: null,
        teachPlanName: null,
        classType: null,
        subjectType: null,
        teachPlanDays: null,
        content: null,
        demands: null,
        teachTimes: null,
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        eduTeachCoursewareList: null,
        eduTeachContentList: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.teachPlanId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleTabChange() {
      if("third" === this.activeName) {
        this.fileList = []
         this.teachPlanList.forEach(plan => {
          if(plan.teachPlanId === this.form.teachPlanId) {
            plan.eduTeachCoursewareList.forEach(ware => {
              this.fileList.push(  {name: ware.fileName, url: ware.fileUrl})  
            })
          }
        })
      }

    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加教学计划信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const teachPlanId = row.teachPlanId || this.ids
      getTeachPlan(teachPlanId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改教学计划信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.teachPlanId != null) {
            //console.log('--------'+ JSON.stringify(this.form))
            updateTeachPlan(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTeachPlan(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const teachPlanIds = row.teachPlanId || this.ids;
      this.$confirm('是否确认删除教学计划信息编号为"' + teachPlanIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTeachPlan(teachPlanIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有教学计划信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportTeachPlan(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    //******************************* content start *********** */
    resetContent() {
      this.formContent = {
        contentId: null,
        teachPlanId: null,
        courseTimes: null,
        content: null,
        keyPoints: null,
        targets: null,
        methods: null,
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("formContent");
    },
    getContentList() {
      listTeachContentByPlanId(this.form.teachPlanId).then(response => {
        this.teachContentList = response.rows;
      });
    },
    cancelContent() {
      this.openContent = false;
      this.resetContent();
    },
    expandChange(row) {
      //console.log(JSON.stringify(row))
      this.$refs.table.toggleRowExpansion(row)
      this.expandRow = null
    },
    /** 新增按钮操作 */
    handleAddContent(row) {
      this.resetContent();
      this.formContent.teachPlanId = row.teachPlanId
      this.expandRow = row
      this.openContent = true;
      this.titleContent = "添加教学计划上课内容";
    },
    /** 修改按钮操作 */
    handleUpdateContent(row) {
      this.resetContent();
      const contentId = row.contentId
      getTeachContent(contentId).then(response => {
        this.formContent = response.data;
        this.openContent = true;
        this.titleContent = "修改教学计划上课内容";
      });
    },
    /** 提交按钮 */
    submitFormContent() {
      this.$refs["formContent"].validate(valid => {
        if (valid) {
          if (this.formContent.contentId != null) {
            updateTeachContent(this.formContent).then(response => {
              this.msgSuccess("修改成功");
              this.openContent = false;
              this.getList();
              //this.expandChange(this.expandRow)
            });
          } else {
            let v_exists = false
            //console.log(JSON.stringify(this.expandRow))
            if(undefined !== this.expandRow.eduTeachContentList 
              && null !== this.expandRow.eduTeachContentList ) {
              this.expandRow.eduTeachContentList.forEach(content => {
                //console.log(this.formContent.courseTimes)
                if(parseInt(content.courseTimes) === parseInt(this.formContent.courseTimes)) {
                  this.msgSuccess("课次已存在");
                  v_exists = true
                }
              })
            }

            if(!v_exists) {
              addTeachContent(this.formContent).then(response => {
                this.msgSuccess("新增成功");
                this.openContent = false;
                this.getList();
                //this.expandChange(this.expandRow)
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDeleteContent(row) {
      const contentIds = row.contentId;
      this.$confirm('是否确认删除教学计划上课内容编号为"' + contentIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTeachContent(contentIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    // ********************************* content end ************
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$alert(response.msg, "上传结果", { dangerouslyUseHTMLString: true });
      let courseware = {
        fileName : file.name,
        filePath : response.fileName,
        fileUrl : response.url,
       }
      this.form.eduTeachCoursewareList.push(courseware)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleRemove(file, fileList) {
      //console.log(file, fileList);
      this.form.eduTeachCoursewareList.forEach(ware => {
        ware.status = 1
        ware.delFlag = 1
      })
    },
  }
};
</script>
